<template>
  <div class="parameter-editor">
    <div class="header">
      <h3 class="title">参数编辑器</h3>
      <el-button
        v-if="!isViewMode"
        type="primary"
        class="add-btn"
        @click="addParam"
      >
        <i class="el-icon-plus"></i> 添加参数
      </el-button>
    </div>

    <el-table :data="localParams" border class="params-table" v-if="localParams.length > 0">
      <el-table-column prop="paramName" label="参数名称" width="220">
        <template #default="scope">
          <el-autocomplete
            v-model="scope.row.paramName"
            :fetch-suggestions="querySearchAsync(scope.$index)"
            placeholder="请输入参数名称"
            :disabled="isViewMode"
            class="param-input"
            @select="handleSelect(scope.$index, $event)"
            @blur="checkDuplicate(scope.$index)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="paramValue" label="参数值">
        <template #default="scope">
          <el-input
            v-model="scope.row.paramValue"
            placeholder="请输入参数值"
            :disabled="isViewMode"
            class="param-input"
            @input="handleInput(scope.$index)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="unit" label="单位" width="150">
        <template #default="scope">
          <el-input
            v-model="scope.row.unit"
            placeholder="请输入单位"
            :disabled="isViewMode"
            class="param-input"
          />
        </template>
      </el-table-column>

      <el-table-column
        v-if="!isViewMode"
        label="操作"
        width="90"
        align="center"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeParam(scope.$index)"
            class="delete-btn"
          />
        </template>
      </el-table-column>
    </el-table>

    <div v-else class="empty-state">
      <i class="el-icon-document"></i>
      <p>暂无参数数据</p>
    </div>
  </div>
</template>

<script>
import { getParamSuggestions } from '@/api/repair/repairBlade'
export default {
  name: "ParameterEditor",
  props: {
    isViewMode: {
      type: Boolean,
      default: false
    },
    params: {
      type: Array,
      default: () => []
    },
    // 新增参数类型 prop
    paramType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      // 创建本地副本
      localParams: [...this.params],
      timeout: null
    };
  },
  watch: {
    params(newVal) {
      // 当父组件传入的参数变化时更新本地副本
      this.localParams = [...newVal];
    }
  },
  methods: {
    //获取所有参数
    getAllParams() {
      return this.localParams;
    },
    //检查参数名是否重复
    checkDuplicate(index) {
      const currentName = this.localParams[index].paramName;
      if (!currentName) return;

      const duplicates = this.localParams.filter(
        (param, i) =>
          i !== index &&
          param.paramName === currentName
      );

      if (duplicates.length > 0) {
        this.$message.error(`参数名 "${currentName}" 已存在`);
        // 清空当前参数名
        this.$set(this.localParams[index], 'paramName', '');
      }
    },
    addParam() {
      const newParam = {
        paramName: "",
        paramValue: "",
        unit: "",
        sort: this.localParams.length
      };
      this.localParams.push(newParam);
      this.emitChange();
    },
    removeParam(index) {
      this.$confirm('确定要删除该参数吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.localParams.splice(index, 1);
        // 更新剩余参数的排序
        this.localParams.forEach((item, idx) => {
          item.sort = idx;
        });
        this.emitChange();
        this.$message.success('参数删除成功');
      }).catch(() => {
        this.$message.warning('已取消删除');
      });
    },
    emitChange() {
      // 通知父组件参数已变化
      this.$emit("params-change", [...this.localParams]);
    },
    getParams() {
      return this.localParams
        .filter(item => item.paramName && item.paramValue)
        .map(item => ({
          paramName: item.paramName,
          paramValue: item.paramValue,
          unit: item.unit || "",
          sort: item.sort
        }));
    },
    // 修改参数名称查询方法
    querySearchAsync(index) {
      return (queryString, cb) => {
        if (this.timeout) {
          clearTimeout(this.timeout);
        }
        this.timeout = setTimeout(() => {
          // 调用修改后的接口
          getParamSuggestions(this.paramType).then(response => {
            if (response.code === 200) {
              const suggestions = response.data
                .filter(item => item.paramName.toLowerCase().includes(queryString.toLowerCase()))
                .map(item => ({
                  value: item.paramName,
                  unit: item.unit
                }));
              cb(suggestions);
            } else {
              cb([]);
            }
          }).catch(() => {
            cb([]);
          });
        }, 300);
      };
    },
    handleSelect(index, item) {
      this.$set(this.localParams[index], 'paramName', item.value);
      this.$set(this.localParams[index], 'unit', item.unit);
      this.emitChange();
    },
    handleInput(index) {
      let value = this.localParams[index].paramValue;
      // 移除所有非数字、非负号、非小数点的字符
      value = value.replace(/[^0-9.-]/g, '');

      // 处理负号，确保负号仅出现在首位且只有一个
      if (value.indexOf('-') > 0) {
        value = value.replace(/-/g, '');
      }
      if ((value.match(/-/g) || []).length > 1) {
        value = '-' + value.replace(/-/g, '');
      }

      // 处理小数点，确保只有一个小数点
      const dotIndex = value.indexOf('.');
      if (dotIndex !== -1) {
        value = value.slice(0, dotIndex + 1) + value.slice(dotIndex + 1).replace(/\./g, '');
      }

      // 处理以小数点开头的情况，补 0
      if (value.startsWith('.')) {
        value = '0' + value;
      }

      // 处理多 0 开头的整数部分
      if (value.includes('.')) {
        const [integerPart, decimalPart] = value.split('.');
        let newIntegerPart = integerPart.replace(/^(-?)0+/, '$1');
        if (newIntegerPart === '' || newIntegerPart === '-') {
          newIntegerPart = newIntegerPart + '0';
        }
        value = newIntegerPart + '.' + decimalPart;
      } else {
        value = value.replace(/^(-?)0+/, '$1');
        if (value === '' || value === '-') {
          value = value + '0';
        }
      }

      this.$set(this.localParams[index], 'paramValue', value);
    },
  },
}
</script>

<style lang="scss" scoped>
.parameter-editor {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 20px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;

  &:hover {
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f2f5;

    .title {
      color: #303133;
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      display: flex;
      align-items: center;

      &::before {
        content: "";
        display: inline-block;
        width: 4px;
        height: 18px;
        background: #409EFF;
        border-radius: 2px;
        margin-right: 10px;
      }
    }
  }

  .add-btn {
    background: linear-gradient(135deg, #409EFF, #66b1ff);
    border: none;
    border-radius: 6px;
    padding: 8px 15px;
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
    transition: all 0.3s ease;

    i {
      margin-right: 5px;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(64, 158, 255, 0.4);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .params-table {
    border-radius: 8px;
    overflow: hidden;

    ::v-deep .el-table__header-wrapper {
      th {
        background: linear-gradient(120deg, #f0f7ff, #e6f7ff);
        color: #409EFF;
        font-weight: 600;
        font-size: 15px;
        border-bottom: 1px solid #dcdfe6;
      }
    }

    ::v-deep .el-table__body {
      tr {
        transition: all 0.2s;

        &:hover {
          td {
            background-color: #f5f9ff !important;
          }
        }
      }

      td {
        padding: 8px 0;
        border-bottom: 1px solid #f0f2f5;
      }
    }

    .param-input {
      ::v-deep .el-input__inner {
        border: none;
        background: transparent;
        padding: 0 10px;
        height: 36px;
        transition: all 0.3s;

        &:focus {
          background: #f5f9ff;
          box-shadow: inset 0 0 0 1px #409EFF;
          border-radius: 4px;
        }

        &:hover:not(:focus) {
          background: #f5f9ff;
        }
      }
    }

    .delete-btn {
      background: #fff;
      border: 1px solid #f56c6c;
      color: #f56c6c;
      transition: all 0.3s;
      padding: 6px;

      &:hover {
        background: #fef0f0;
        transform: scale(1.1);
      }
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    color: #909399;
    background: #fafbfc;
    border-radius: 8px;
    border: 1px dashed #dcdfe6;

    i {
      font-size: 48px;
      margin-bottom: 15px;
      color: #c0c4cc;
    }

    p {
      margin: 0;
      font-size: 15px;
    }
  }
}
</style>
